package com.hutao.manage.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hutao.manage.pojo.LeftMenuPojo;
import com.hutao.manage.query.MedRecordQuery;
import com.hutao.manage.query.MedTraceQuery;
import com.hutao.manage.service.BasicInfoService;
import com.hutao.manage.service.HospNoteBasicJsonService;
import com.hutao.manage.service.MedRecordService;
import com.hutao.manage.service.TreatmentTraceService;
import com.hutao.manage.util.DateUtil;
import com.hutao.manage.util.ExcelUtil;
import com.hutao.manage.util.JsonUtils;
import com.hutao.manage.util.Result;

@Controller
@RequestMapping("/statistics")
public class StatisticsController {
	
	@Autowired
	private MedRecordService medRecordService;
	
	@Autowired
	private BasicInfoService basicInfoService;
	
	@Autowired
	private TreatmentTraceService treatmentTraceService;
	
	@Autowired
	private HospNoteBasicJsonService hospNoteBasicJsonService;
	
	@GetMapping("/collectionStatistics")
	public String collectionStatistics(MedTraceQuery params,String beyondDay,Model model){
		
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("collection_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		Map<String, Object> collectionStatistics = new HashMap<String, Object>();
		int beyondDays = 2;
		try{
			beyondDays = Integer.parseInt(beyondDay);
		}catch (Exception e) {
			// TODO: handle exception
		}
		beyondDay= String.valueOf(beyondDays);
		
		List<Map<String,Object>> medicalOffices = basicInfoService.getMedicalOfficesByHospitalId(1);
		
		if(isNullParams(params)){
			collectionStatistics = medRecordService.statisticsMedRecordOfPigeonhole(params,beyondDays);
		}
		model.addAttribute("pageJson", JsonUtils.objectToJson(params));
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("collectionStatistics", collectionStatistics);
		model.addAttribute("medTraceQuery", params);
		model.addAttribute("beyondDay", beyondDay);
		model.addAttribute("offices", medicalOffices);
		return "statistics/collectionStatistics.page";
	}
	
	
	public  boolean isNullParams(MedTraceQuery params){
		if(params==null){
			return false;
		}
		if(StringUtils.isEmpty(params.getMrId()) && params.getOutHospitalStartDate()==null && params.getOutHospitalEndDate()==null && params.getTraceStartDate()==null && params.getTraceEndDate()==null && params.getOutHospitalOfficeId()==null){
			return false;
		}
		return true;
	}
	
	@GetMapping("/returnMedRecordPage")
	public String returnMedRecordPage(MedTraceQuery params,String beyondDay,Model model){
		
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("upload_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		Map<String, Object> collectionStatistics = new HashMap<String, Object>();
		int beyondDays = 0;
		try{
			//beyondDays = Integer.parseInt(beyondDay);
		}catch (Exception e) {
			// TODO: handle exception
		}
		beyondDay= String.valueOf(beyondDays);
		if(params.getTraceStartDate()!= null && params.getTraceEndDate() != null){
			collectionStatistics = medRecordService.statisticsMedRecordOfPigeonhole(params,beyondDays);
		}
		model.addAttribute("pageJson", JsonUtils.objectToJson(params));
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("collectionStatistics", collectionStatistics);
		model.addAttribute("medTraceQuery", params);
		model.addAttribute("beyondDay", beyondDay);
		return "statistics/returnMedRecordPage";
	}
	
	
	@GetMapping("/returnMedRecord")
	public String  returnMedRecord(Model model){
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("upload_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		model.addAttribute("leftMenuJson", leftMenuJson);
		return "statistics/returnMedRecord";
	}
	
	/*@GetMapping("/ajaxCollectionStatistics")
	@ResponseBody
	public Result ajaxCollectionStatistics(MedRecordQuery params,String beyondDay,Model model,HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> collectionStatistics = new HashMap<String, Object>();
		int beyondDays = 2;
		try{
			beyondDays = Integer.parseInt(beyondDay);
		}catch (Exception e) {
			// TODO: handle exception
		}
		beyondDay= String.valueOf(beyondDays);
		if(params.getOutHospitalStartDate() != null && params.getOutHospitalEndDate() != null){
			collectionStatistics = medRecordService.statisticsMedRecordOfPigeonhole(params,beyondDays);
		}
		resultMap.put("collectionStatistics", collectionStatistics);
		resultMap.put("medRecordQuery", params);
		resultMap.put("beyondDay", beyondDay);
		Result result= new Result(true, "查询成功!",resultMap);
		return result;
	}*/
	@GetMapping("/collectionReportToExcel")
	public void collectionReportToExcel(MedTraceQuery params,String beyondDay,HttpServletResponse response) {
		String[] headers = { "姓名", "病案号", "住院号", "出院科室", "出院日期", "归档日期", "迟送天数" };
		OutputStream out;
		Map<String, Object> collectionStatistics = new HashMap<String, Object>();
		int beyondDays = 2;
		try{
			beyondDays = Integer.parseInt(beyondDay);
		}catch (Exception e) {
			// TODO: handle exception
		}
		beyondDay= String.valueOf(beyondDays);
		if(!params.IsPropertyEmpty()){
			collectionStatistics = medRecordService.statisticsMedRecordOfPigeonhole(params,beyondDays);
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> collectResult =(Map<String, Object>)collectionStatistics.get("collectResult");
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> collectionOfMedRecords =(List<Map<String, Object>>)collectionStatistics.get("detail");
		List<String> keys = new ArrayList<String>();
		keys.add("patient_name");
		keys.add("mr_id");
		keys.add("only_id");
		keys.add("office_name");
		keys.add("out_hospital_date");
		keys.add("trace_date");
		keys.add("date_diff");
		
		try{
			
			response.setContentType("octets/stream");
			String title= "数据导出";
			
			StringBuilder downLoadFileName = new StringBuilder();
			if(collectResult.get("collectTotal") != null){
				if(params.getTraceStartDate()!= null && params.getTraceEndDate()!= null){
					title = new StringBuilder().append(DateUtil.dateFormat(params.getTraceStartDate())).append("到").append(DateUtil.dateFormat(params.getTraceEndDate()))
							.append("的报表").append("---").append(beyondDays).append("日归档率为：").append(collectResult.get("collectRate")).append("%").toString();
				}else if(params.getOutHospitalStartDate()!= null && params.getOutHospitalEndDate()!= null){
					title = new StringBuilder().append(DateUtil.dateFormat(params.getOutHospitalStartDate())).append("到").append(DateUtil.dateFormat(params.getOutHospitalEndDate()))
							.append("的报表").append("---").append(beyondDays).append("日归档率为：").append(collectResult.get("collectRate")).append("%").toString();
				}else{
					title = new StringBuilder().append("归档报表").append("---").append(beyondDays).append("日归档率为：").append(collectResult.get("collectRate")).append("%").toString();
				}
				
				downLoadFileName = new StringBuilder(
						"attachment;filename=");
				downLoadFileName.append(title)
						.append(".xls");
			}else{
				downLoadFileName = new StringBuilder(
						"attachment;filename=");
				if(params.getTraceStartDate()!= null && params.getTraceEndDate()!= null){
					title = new StringBuilder().append(DateUtil.dateFormat(params.getTraceStartDate())).append("到").append(DateUtil.dateFormat(params.getTraceEndDate()))
							.append("的报表").append("---").append(beyondDays).append("日无迟送病案").toString();
				}else if(params.getOutHospitalStartDate()!= null && params.getOutHospitalEndDate()!= null){
					title = new StringBuilder().append(DateUtil.dateFormat(params.getOutHospitalStartDate())).append("到").append(DateUtil.dateFormat(params.getOutHospitalEndDate()))
							.append("的报表").append("---").append(beyondDays).append("日无迟送病案").toString();
				}else{
					title = new StringBuilder().append("归档报表").append("---").append(beyondDays).append("日无迟送病案").toString();
				}
				downLoadFileName.append(title)
						.append(".xls");
			}
			
			String encodeStr = new String(downLoadFileName.toString().getBytes(
					"GB2312"), "ISO_8859_1");
			response.addHeader("Content-Disposition", encodeStr);
			out = response.getOutputStream();
			ExcelUtil.exportExcel(out, title, headers, keys, collectionOfMedRecords);
			out.flush();
			out.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 
	 * 归档工作量统计
	 * 
	 * @param dateFiling
	 * @return
	 */
	@GetMapping("/ajax_getWorkloadStatisticsDateOfFiling")
	@ResponseBody
	public Result getWorkloadStatisticsDateOfFiling(String beginDate, String endDate, HttpServletResponse response) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			
			Map<String, Object> params = new HashMap<>();
			params.put("beginDate", beginDate);
			params.put("endDate", endDate);
			
			List<Map<String, Object>> list = treatmentTraceService.getWorkloadStatisticsDateOfFiling(params); 
			return new Result(true, "查询成功!", list, 200);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "系统异常!", null, 500);
		}
		
	}
	
	/**
	 * 
	 * 质控工作量统计
	 * 
	 * @param dateFiling
	 * @return
	 */
	@GetMapping("/ajax_getWorkloadStatisticsQualityControl")
	@ResponseBody
	public Result ajax_getWorkloadStatisticsQualityControl(String beginDate, String endDate, HttpServletResponse response) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			
			Map<String, Object> params = new HashMap<>();
			params.put("beginDate", beginDate);
			params.put("endDate", endDate);
			
			List<Map<String, Object>> list = treatmentTraceService.getWorkloadStatisticsQualityControl(params); 
			return new Result(true, "查询成功!", list, 200);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "系统异常!", null, 500);
		}
		
	}
	
	/**
	 * 编页工作量统计
	 * 
	 * @param beginDateFiling
	 * @param endDateFiling
	 * @param response
	 * @return
	 */
	@GetMapping("/ajax_getWorkloadStatisticsPagenation")
	@ResponseBody
	public Result ajax_getWorkloadStatisticsPagenation(String beginDate, String endDate, HttpServletResponse response) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			
			Map<String, Object> params = new HashMap<>();
			params.put("beginDate", beginDate);
			params.put("endDate", endDate);
			
			List<Map<String, Object>> list = treatmentTraceService.getWorkloadStatisticsPagenation(params); 
			return new Result(true, "查询成功!", list, 200);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "系统异常!", null, 500);
		}
		
	}
	
	
	/**
	 * 编目工作量统计
	 * 
	 * @param beginDateFiling
	 * @param endDateFiling
	 * @param response
	 * @return
	 */
	@GetMapping("/ajax_getWorkloadStatisticsCatalog")
	@ResponseBody
	public Result ajax_getWorkloadStatisticsCatalog(String beginDate, String endDate, HttpServletResponse response) {
		
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			
			Map<String, Object> params = new HashMap<>();
			params.put("beginDate", beginDate);
			params.put("endDate", endDate);
			
			List<Map<String, Object>> list = treatmentTraceService.getWorkloadStatisticsCatalog(params); 
			return new Result(true, "查询成功!", list, 200);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "系统异常!", null, 500);
		}
		
	}
	
	@PostMapping("/ajax_getMainDiagnoseDiseaseTop12")
	@ResponseBody
	public Result ajax_getMainDiagnoseDiseaseTop12(String beginOutHospitalDate, String endOutHospitalDate, String outDeptName,
			HttpServletResponse response) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			
			Map<String, Object> params = new HashMap<>();
			params.put("beginOutHospitalDate", beginOutHospitalDate);
			params.put("endOutHospitalDate", endOutHospitalDate);
			params.put("outDeptName", outDeptName);
			List<Map<String, Object>> list = hospNoteBasicJsonService.ajax_getMainDiagnoseDiseaseTop12(params);
			
			return new Result(true, "查询成功!", list);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "查询失败!");
		}
		
	}
	
	@PostMapping("/ajax_getSecondDiagnoseDiseaseTop12")
	@ResponseBody
	public Result ajax_getSecondDiagnoseDiseaseTop12(String beginOutHospitalDate, String endOutHospitalDate, String outDeptName,
			HttpServletResponse response) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			
			Map<String, Object> params = new HashMap<>();
			params.put("beginOutHospitalDate", beginOutHospitalDate);
			params.put("endOutHospitalDate", endOutHospitalDate);
			params.put("outDeptName", outDeptName);
			List<Map<String, Object>> list = hospNoteBasicJsonService.ajax_getSecondDiagnoseDiseaseTop12(params);
			
			return new Result(true, "查询成功!", list);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "查询失败!");
		}
		
	}
	
	@PostMapping("/ajax_getMainOperationTop")
	@ResponseBody
	public Result ajax_getMainOperationTop(String beginOutHospitalDate, String endOutHospitalDate, String outDeptName,
			HttpServletResponse response) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			Map<String, Object> params = new HashMap<>();
			params.put("beginOutHospitalDate", beginOutHospitalDate);
			params.put("endOutHospitalDate", endOutHospitalDate);
			params.put("outDeptName", outDeptName);
			List<Map<String, Object>> list = hospNoteBasicJsonService.ajax_getMainOperationTop(params);
			
			return new Result(true, "查询成功!", list);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "查询失败!");
		}
		
	}
	
	/**
	 * 缺项统计
	 * 
	 * @return
	 */
	@GetMapping("/ajax_lacunaStatistics")
	@ResponseBody
	public Result ajax_lacunaStatisticsPage(MedRecordQuery params, HttpServletResponse response) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			Map<String,Object> resultMap = new HashMap<String, Object>();
			
			List<Map<String,Object>> hospitalizationNotes = medRecordService.getLacunaStatisticsPage(params);
			
			if (hospitalizationNotes != null && hospitalizationNotes.size() > 0) {
				for(Map<String, Object> map : hospitalizationNotes) {
					String firstGuid = (String) map.get("first_level_medical_guid");
					String codeStr = medRecordService.getLacunaCodeStrByFirstGuid(firstGuid);
					StringBuilder lacunaContent = new StringBuilder();
					
					if (StringUtils.isBlank(codeStr)) {
						lacunaContent.append("病案首页,入院记录,病程记录,医嘱记录单 ,");
					} else {
						String [] codes = codeStr.split(",");
						int a = 0;
						int b = 0;
						int c = 0;
						int d = 0;
						
						for (String s : codes) {
							if (s.equals("1")) {
								a = 1;
							} else if (s.equals("3")) {
								b = 1;
							} else if (s.equals("4")) {
								c = 1;
							} else if (s.equals("24")) {
								d = 1;
							}
						}
						
						if (a == 0) {
							lacunaContent.append("病案首页,");
						}
						
						if (b == 0) {
							lacunaContent.append("入院记录,");
						}
						
						if (c == 0) {
							lacunaContent.append("病程记录,");
						}
						
						if (d == 0) {
							lacunaContent.append("医嘱记录单,");
						}
						
						
					}
					
					String lacunaContentStr = lacunaContent.toString();
					
					if (StringUtils.isNotBlank(lacunaContentStr)) {
						lacunaContentStr = lacunaContentStr.substring(0, lacunaContentStr.length()-1);
					}
					
					map.put("lacunaContent", lacunaContentStr);
				}
			}
			
			int count = medRecordService.getLacunaStatisticsCountPage(params);
			
			params.setTotalCounts(count);
			resultMap.put("count", count);
			resultMap.put("hospitalizationNotes", hospitalizationNotes);
			Result result= new Result(true, "查询成功!",resultMap);
			
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "查询失败!");
		}
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
